<template>
    <div>
           <!--面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

          <!--卡片视图区域-->
        <el-card class="box-card">   
          <!--表格头-->
            <el-row :gutter="30">
            <el-col :span="8">
                 <el-button type="primary" @click="addDataDialog">添加角色</el-button>
            </el-col>
            </el-row>
               <!--用户列表区域-->
            <el-table :data="roleList" border stripe >
                <el-table-column type=expand label=">>">
                    <!--角色权限信息-->
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',index1===0?'bdtop':'','vcenter']" v-for="(itme1,index1) in scope.row.children" :key="itme1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightByid(scope.row,itme1.id)">  {{itme1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <!-- 通过for循环 嵌套渲染二级权限-->
                                <el-row  :class="[index2===0?'':'bdtop','vcenter']" v-for="(itme2,index2) in itme1.children" :key="itme2.id" >
                                    <!-- 左边放二级 -->
                                <el-col :span="6">
                                    <el-tag type="success" closable @close="removeRightByid(scope.row,itme2.id)" >  {{itme2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col >
                                    <!-- 右侧放三级 -->
                                <el-col :span="18">
                                     <el-tag type="warning"  v-for="item3 in itme2.children" :key="item3.id" closable @close="removeRightByid(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                </el-col>

                                </el-row>

                            </el-col>
                           
                        </el-row>

                        <!-- <pre> {{scope.row.children}}</pre> -->
                       
                    </template>
                </el-table-column>
                <el-table-column type=index label="#"></el-table-column>
                <el-table-column prop="id" label="ID" ></el-table-column>
                <el-table-column prop="roleName" label="角色名字" ></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column  label="操作" width='200px'>

                <template slot-scope="scope">
                  <!--修改按钮-->
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDataDialog(scope.row)"></el-button>
                  <!--删除按钮-->
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataByid(scope.row.id)"></el-button>

                 <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable='false' >
                 <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)"></el-button>
                </el-tooltip>
                </template>
                </el-table-column>  
            </el-table>

            <!--分页区域-->
           <!-- <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page='queryInfo.pagenum'
            :page-sizes="[10, 20, 2,1]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination> -->

        </el-card> 

           <!--分配权限的对话框  -->
         <el-dialog
            title="角色权限分配"
            :visible.sync="showSetRightDialogVisible"
            width="50%"
            @close="setEighrDialogClosed"
            >
            <!-- 树形结构数据 -->
               <el-tree
                :data="rightList"
                show-checkbox
                node-key="id"
                default-expand-all
               :default-checked-keys="hasRightList"
                :props="treeProps"
                ref="treeRef">
                </el-tree>
            
           <!-- 底部 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="showSetRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allcheckRight">确 定</el-button>
            </span>
        </el-dialog>

<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
          <!--添加编辑角色对话框-->   
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dataDiglogVisble"
            width="50%"
            @close="clearForm" >
            <!--内容主体区域-->
            <el-form :model="DataFrom" :rules="DataFromRules" ref="DataFormRef" label-width="100px" class="demo-ruleForm">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="DataFrom.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="DataFrom.roleDesc" ></el-input>
            </el-form-item>
            </el-form>
            <!--底部区域-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="dataDiglogVisble = false">取 消</el-button>
                <el-button type="primary" @click="submissionData">确 定</el-button>
            </span>
        </el-dialog>


    </div>
</template>
<script>
export default {
    data() {
        return {
            //角色列表数据(拥有)
            roleList:[],
            showSetRightDialogVisible:false,
            //权限树形数据(全部)
            rightList:[],
            //树形控件的属性绑定对象
            treeProps:{
                 children: 'children',
                 label: 'authName'
            },
            //默认选中的权限
             hasRightList:[],
             //角色id
             roleId:'',
            //  =================添加=========================
             //控制添加对话框是否显示
             dataDiglogVisble:false,
             DataFrom:{
                 roleId:'',
                 roleName:'',
                 roleDesc:''
             },
             dialogTitle:'',
             //数据表单规则验证
           DataFromRules:{
                roleName:[
                   { required: true, message: '请输入角色名称', trigger: 'blur' },
                   { min: 1, max: 12, message: '长度在 1 到12 个字符', trigger: 'blur' }
                ],
                 roleDesc:[
                   { required: true, message: '请输入描述', trigger: 'blur' },
                   { min: 1, max: 25, message: '密码长度在 1 到25个字符', trigger: 'blur' }
                ]
       
            },
        //=======================分页参数(后台未提供)===========================
         queryInfo:{
            //条件查询对象
            query:'',
            //当前页
            pagenum:1,
            //当前页每页数据
            pagesize:5
            },
            total:0,
            pageList:[]

        }
    },
    created() {
       this.getRolesList()
    },
    methods: {
        //获取角色列表
        getRolesList(){
            this.$my_http({
                  method:"get",
                  url:"roles",

                }).then(res => {
                    if(res.data.meta.status != 200){
                      this.$message.error("获取数据失败");
                    }else{  
                   this.roleList=res.data.data
                  // console.log(this.roleList)
          
                 }
                }) 
        },
//=========================================  

        //显示对话框
        addDataDialog(){
            //修改标题
            this.dialogTitle="添加角色"
            this.dataDiglogVisble=true;
        },
     
        //添加方法
        addData(){       
            //验证表单数据
               this.$refs.DataFormRef.validate(valid=>{
                console.log(valid);    
                if(!valid)  return;

              //提交数据
                  this.$my_http({
                    method:"post",
                    url:'roles',
                    data:this.DataFrom
                }).then(res => {
                    if(res.data.meta.status != 201){
                      this.$message.error(res.data.meta.msg);
                       this.dataDiglogVisble=false
                    }else{  
                     this.$message({ type: 'success', message: '创建角色成功!'});
                         this.dataDiglogVisble=false;
                         this.getRolesList();
                   
                 }
                }) 
                             
            })

        }, 
        //监听表单关闭事件，清空数据
       clearForm(){
            this.$refs.DataFormRef.resetFields();//重置表单  
            this.DataFrom.roleId='';//id清空
            this.DataFrom.roleName ='';
           this.DataFrom.roleDesc='';        
           
       },
        //点击确认按钮
        submissionData(){
            console.log(this.DataFrom.roleId)
            //有id编辑
            if(this.DataFrom.roleId){
                //  console.log("=====编辑=====")
                this.editData()   
            }else{
                 //  console.log("=====添加=====")
               this.addData();
            }
        },
     //========修改角色==============
       //显示对话框
       editDataDialog(data){
           console.log(data)
           this.DataFrom.roleName =data.roleName;
           this.DataFrom.roleDesc=data.roleDesc;
           this.dialogTitle="编辑角色"
           this.DataFrom.roleId=data.id       
            this.dataDiglogVisble=true;         
            
       },
         //修改方法
        editData(){
                this.$refs.DataFormRef.validate( valid=>{
                    if(!valid) return
                    //发起数据请求
                    this.$my_http({
                    method:"put",
                    url:`roles/${this.DataFrom.roleId}`,
                    data:this.DataFrom
                    }).then(res => {
                        if(res.data.meta.status != 200){
                        this.$message.error(res.data.meta.msg);
                        this.dataDiglogVisble=false
                        }else{  

                            this.dataDiglogVisble=false;
                            this.getRolesList();
                            this.$message({ type: 'success', message: '修改角色成功!'});
                            
                    
                        }
                 }) 


                 });    
        },
    //===============================================   
        //删除角色
       removeDataByid(id){

         //确认删除则返回字符串 confirm;点击取消则报错（可使用catch 捕获错误）
          this.$confirm('正在删除用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {

                   //确认提交     
                  this.$my_http({
                    method:"delete",
                    url:`roles/${id}`,
                }).then(res => {
                    if(res.data.meta.status != 200){
                      this.$message.error(res.data.meta.msg);
                     
                    }else{  
                     this.$message({ type: 'success', message: '删除角色成功!'});                      
                     this.getRolesList();
                   
                 }
                }) 
                        

                }).catch(() => {

                this.$message({ type: 'info',message: '已取消删除' });          
              });
                        
       },
     
//================================================================       
        //删除角色权限
        removeRightByid(role,rightId){
             //确认删除则返回字符串 confirm;点击取消则报错（可使用catch 捕获错误）
          this.$confirm('正在删除角色权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then( () => {
                  //请求  
                this.$my_http({
                    method:"delete",
                    url:`roles/${role.id}/rights/${rightId}`,
                }).then(res => {
                    if(res.data.meta.status != 200){
                      this.$message.error("删除失败");
                    }else{  
                     this.$message({ type: 'success', message: '删除成功!'});
                    //后台返回最新的角色数据(方法中的数据能直接改变页面数据)
                     role.children=res.data.data
                 }
                }) 

                }).catch(() => {
                this.$message({ type: 'info',message: '已取消删除' });          
              });
           
        },
        //展示分配角色权限
        showSetRightDialog(role){
            //获取当前角色id
           this.roleId=role.id
                //请求  
                this.$my_http({
                    method:"get",
                    url:`rights/tree`,
                }).then(res => {
                    if(res.data.meta.status != 200){
                      this.$message.error("获取权限失败");
                    }else{  
                     console.log(res.data.data)
                     this.rightList=res.data.data
                     //递归获取三级节点信息
                     this.getleafKey(role,this.hasRightList)
                    this.showSetRightDialogVisible=true;
                 }
                });
        },
        //递归获取角色拥有的三级权限id
        //node当前节点，arr数组
        getleafKey(node,arr){
            //如果不包含children则是三级节点
            if(!node.children){
                return arr.push(node.id)
            }
            //否则递归该节点
            node.children.forEach(item => {
                this.getleafKey(item,arr)
            });
               
        },
        //监听树形对话框关闭，清空保存的数据
        setEighrDialogClosed(){
            this.hasRightList=[]
        },
        //点击为角色分配权限
        allcheckRight(){
            const keys =[
                //...为展开运算符
                //返回目前被选中的节点的 key 所组成的数组
                ...this.$refs.treeRef.getCheckedKeys(),
                //则返回目前半选中的节点的 key 所组成的数组
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
          //  console.log(keys)
          const keyStr =keys.join(',');

              //请求  
                this.$my_http({
                    method:"post",
                    url:`roles/${this.roleId}/rights`,
                    data:{
                         rids:keyStr
                    }
                }).then(res => {
                    if(res.data.meta.status != 200){
                      this.$message.error("角色授权失败");
                    }else{  
                    this.$message.success("角色授权成功");
                    //关闭并刷新
                    this.showSetRightDialogVisible=false;
                    this.getRolesList;

                 }
                });

        }
    },
}
</script>
<style lang="less" scoped>
.el-tag{
   margin: 7px;
}
.bdtop{
    border-top: 1px solid #eeeeee;
}
.bdbottom{
    border-bottom: 1px solid #eeeeee;
}
.vcenter{
    display: flex;
    align-items: center;
}

</style>